// https://thebookofshaders.com/07/?lan=ch
import { 
  Camera,  
  Color,  
  Mesh, 
  PlaneBufferGeometry, 
  Scene, 
  ShaderMaterial, 
  Vector3, 
  WebGLRenderer 
} from "three"
import stats from '../../utils/stats'

const canvas = document.createElement('canvas')
document.body.appendChild(canvas)
canvas.style.width = '100vw'
canvas.style.height = '100vh'

const scene = new Scene()
const renderer = new WebGLRenderer({
  antialias: true,
  canvas
})
renderer.autoClearColor = false

const camera = new Camera()
camera.position.z = 1
const plane = new PlaneBufferGeometry(2, 3)

// 片段着色器
const fragmentShader = `
#include <common>

uniform vec2 u_resolution;
uniform float u_time;

void main() {
  vec2 st = gl_FragCoord.xy / u_resolution;
  float pct = 0.0;

  // a. The DISTANCE from the pixel to the center
  // 中心黑色渐变
  // pct = distance(st, vec2(0.5));
  // 反转颜色（中心白色渐变）
  pct = 1.0 - distance(st, vec2(0.5));
  // pct = distance(st, vec2(0.4)) + distance(st, vec2(0.6));
  // pct = distance(st, vec2(0.4)) * distance(st, vec2(0.6));
  // pct = min(distance(st, vec2(0.4)), distance(st, vec2(0.6)));
  // pct = max(distance(st, vec2(0.4)), distance(st, vec2(0.6)));
  // pct = pow(distance(st, vec2(0.4)), distance(st, vec2(0.6)));

  // b. The LENGTH of the vector from the pixel to the center
  // vec2 toCenter = vec2(0.5)-st;
  // pct = length(toCenter);

  // c. The SQUARE ROOT of the vector from the pixel to the center
  // vec2 tC = vec2(0.5)-st;
  // pct = sqrt(tC.x*tC.x+tC.y*tC.y);

  vec3 color = vec3(pct);

  gl_FragColor = vec4(color, 1.0);
}
`

const uniforms = {
  u_time: { value: 0 },
  u_resolution: { value: new Vector3() },
}
const material = new ShaderMaterial({
  fragmentShader,
  uniforms
})
scene.add(new Mesh(plane, material))

function render(time: number) {
  stats.update()
  // 转化成秒
  time *= 0.001

  uniforms.u_time.value = time
  const canvas = renderer.domElement
  uniforms.u_resolution.value.set(canvas.width, canvas.height, 1)

  renderer.render(scene, camera)

  requestAnimationFrame(render)
}

requestAnimationFrame(render)